package com.example.administrator.readbook.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import com.example.administrator.readbook.R;
import com.example.administrator.readbook.adapter.AdapterBookSourceList;
import com.example.administrator.readbook.bean.BookSourceBean;
import com.example.administrator.readbook.http.ServiceFactory;
import com.example.administrator.readbook.http.ServiceUrl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

import static com.example.administrator.readbook.http.ServiceFactory.schedulersTransformer;

public class BookSourceActivity extends AppCompatActivity {
    private ListView listView;
    private List<BookSourceBean> bookSourceList = new ArrayList<>();
    private AdapterBookSourceList adapterBookSourceList;
    private String bookId, bookName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_book_source);
        bookId = getIntent().getStringExtra("bookId");
        bookName = getIntent().getStringExtra("bookName");
        listView = findViewById(R.id.book_source_listview);
        adapterBookSourceList = new AdapterBookSourceList(this, bookSourceList);
        listView.setAdapter(adapterBookSourceList);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(BookSourceActivity.this, ChapterListActivity.class);
                intent.putExtra("bookId", bookSourceList.get(position).get_id());
                intent.putExtra("bookName", bookName);
                startActivity(intent);
            }
        });
        getBookSourceData();
    }

    public void getBookSourceData() {
        HashMap<String, String> params = new HashMap<>();
        params.put("view", "summary");
        params.put("book", bookId);
        ServiceUrl searchService = ServiceFactory.getServiceBook();
        searchService.getBookSourceListData(params).compose(schedulersTransformer).subscribe(new Observer<List<BookSourceBean>>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(List<BookSourceBean> bookSourceBeans) {
                bookSourceList.clear();
                bookSourceList.addAll(bookSourceBeans);
                adapterBookSourceList.notifyDataSetChanged();
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }
}
